//
//  ZNWBBaseViewController.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/7/28.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import UIKit

class ZNWBBaseViewController: UIViewController {
    
    var tableView: UITableView?
    var refreshControl: ZNWBRefreshControl?
    
    var visitorInfo: [String: String]?
    
    var isShouldPullUpRefresh = false
    
    //如果利用系统提供的导航控制器又要自定义返回按钮，侧滑返回的融合效果在快速滑动时容易出现混乱，因此选择自定义导航条
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    lazy var zn_navigationItem = UINavigationItem()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: ZNWBLoginSuccessNotification), object: nil)
        
        setupNavigationBar()
        
        if ZNWBNetworkManager.shared.isLogin {
            setupTableView()
            loadData()
        } else {
            setupVisitorView()
        }
    }
    
    @objc private func loginSuccess() {
        // 如果在使用getter访问view时，如果view为nil。就会依次调用loadView和viewDidLoad，就会再次注册，故此处需要注销通知，防止一个通知响应两次方法
        
        //**核心**
        view = nil
        zn_navigationItem.leftBarButtonItem = nil
        zn_navigationItem.rightBarButtonItem = nil
        
        NotificationCenter.default.removeObserver(self)
    }
    
    //didSet相当于OC中的setter，并且自动完成了数据的刷新
    override var title: String? {
        didSet {
            zn_navigationItem.title = title
        }
    }
    
    deinit {
        // 移除通知
        NotificationCenter.default.removeObserver(self)
    }
}

extension ZNWBBaseViewController {
    fileprivate func setupNavigationBar() {
        navigationBar.items = [zn_navigationItem]
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkGray]
        
        view.addSubview(navigationBar)
    }
    
    func setupTableView() {
        //当导航栏隐藏后，系统会自动将scrollView内容缩进20点显示，这里将它取消
        automaticallyAdjustsScrollViewInsets = false
        
        tableView = UITableView(frame: view.bounds, style: .plain)
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.backgroundColor = UIColor.white
        
        //调整表视图的内容缩进，头部缩进导航栏的高度，尾部缩进标签栏的高度
        tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        // 设置表视图的滚动指示器的缩进
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        
        refreshControl = ZNWBRefreshControl()
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        tableView?.addSubview(refreshControl!)
        
        view.insertSubview(tableView!, belowSubview: navigationBar)
    }
    
    fileprivate func setupVisitorView() {
        let visitorView = ZNWBVisitorView(frame: view.bounds)
        
        visitorView.visitorInfo = visitorInfo
        visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
        visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
        
        view.insertSubview(visitorView, belowSubview: navigationBar)
    }
    
    @objc func login() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: ZNWBLoginNotification), object: nil)
    }
    
    @objc func register() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: ZNWBRegisterNotification), object: nil)
    }
}

extension ZNWBBaseViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    /// 让子类能够重写返回行高的方法，否则子类的方法不会被触发
    ///
    /// - Parameters:
    ///   - tableView: default
    ///   - indexPath: default
    /// - Returns: default
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let currentDisplayRow = indexPath.row
        let maxSection = tableView.numberOfSections - 1
        
        if currentDisplayRow < 0 || maxSection < 0 {
            return
        }
        
        let rowsCount = tableView.numberOfRows(inSection: maxSection)
        
        if currentDisplayRow == rowsCount - 1 && !isShouldPullUpRefresh {
            isShouldPullUpRefresh = true
            print("开始上拉刷新")
            
            loadData()
        }
    }
    
    //如果子控制器没有实现刷新方法，默认关闭刷新控件
    func loadData() {
        refreshControl?.endRefreshing()
    }
}
